package pers.cj.pdos.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pers.cj.pdos.utils.FileProperUtil;
import pers.cj.pdos.utils.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 定时清理临时下载excel文件
 */
@Component
public class CleanTempExcelTask {
    /**
     * 检查周期1小时
     */
    private static final long SECONDS = 60*60*1000;
    //private static final long SECONDS = 20*1000;//测试就30秒
    private static Map<String, Long> tableMap = new HashMap<>();

    //@Scheduled(cron="0 0/30 * * * ?")
    @Scheduled(cron="0/30 * * * * ?")
    public void task() throws IOException {
        Date now = new Date();
        Logger.getLogger(CleanTempExcelTask.class).info("*********清理日常excel文件临时数据任务每30秒执行一次进入任务");
        for (Map.Entry<String, Long> entry : tableMap.entrySet()) {
            long time = entry.getValue();
            String fileName = entry.getKey();
            if (now.getTime() - time > SECONDS) {
                Logger.getLogger(CleanTempExcelTask.class).info("*********文件:" + fileName + "已经到达清理时间");
                //超过时间则清理数据
                String filename = FileProperUtil.getInstance().getVal("excel.temp") + fileName;
                File file = new File(filename);
                if (file.exists()) {
                    file.delete();
                    Logger.getLogger(CleanTempExcelTask.class).info("*********文件:" + fileName + "已删除");
                    remove(fileName);
                } else {
                    Logger.getLogger(CleanTempExcelTask.class).info("*********文件:" + fileName + "不存在");
                }
            } else {
                Logger.getLogger(CleanTempExcelTask.class).info("*********文件:" + fileName + "未到清理时间");
            }
        }
    }

    /**
     * 向定时任务添加表名和时间，存在的则更新
     * @param fileName
     * @param time
     */
    public static void put(String fileName, Long time){
        Logger.getLogger(CleanTempExcelTask.class).info("*********新增要清理的excel文件:" + fileName);
        tableMap.put(fileName, time);
    }

    /**
     * 从定时任务中删除表名
     * @param fileName
     */
    public static void remove(String fileName){
        Logger.getLogger(CleanTempExcelTask.class).info("*********移除要清理的excel文件:" + fileName);
        tableMap.remove(fileName);
    }

}
